//
//  RPNCalcViewController.m
//  RPNCalc
//
//  Created by Jacob V.V. Goldberg on 6/26/12.
//  Copyright (c) 2012 FutureSight Technologies. All rights reserved.
//

#import "RPNCalcViewController.h"
#import "RPNCalcBRAIN.h"

@interface RPNCalcViewController ()
@property (nonatomic) BOOL userIsInTheMiddleOfEnteringANumber;
@property (nonatomic, strong) RPNCalcBRAIN *brain;

@end

@implementation RPNCalcViewController
@synthesize display = _display;
@synthesize plusBtn = _plusBtn;
@synthesize minusBtn = _minusBtn;
@synthesize timesBtn = _timesBtn;
@synthesize divBtn = _divBtn;
@synthesize userIsInTheMiddleOfEnteringANumber = _userIsInTheMiddleOfEnteringANumber;
@synthesize brain = _brain;

-(RPNCalcBRAIN *) brain {
    if (!_brain) {
        _brain = [[RPNCalcBRAIN alloc] init];
    }
    return _brain;
}
- (IBAction)digitPressed:(UIButton *)sender {
     NSString *digit = sender.currentTitle;
    
    if (self.userIsInTheMiddleOfEnteringANumber) {
        self.display.text = [self.display.text stringByAppendingFormat: @"%@", digit];
    } else {
        self.display.text = digit;
        self.userIsInTheMiddleOfEnteringANumber = YES;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
}

- (void)viewDidUnload {
    [self setDisplay:nil];
    [self setPlusBtn:nil];
    [self setMinusBtn:nil];
    [self setTimesBtn:nil];
    [self setDivBtn:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (IBAction)cBtnClicked:(id)sender {
    self.userIsInTheMiddleOfEnteringANumber = NO;
    self.display.text = @"0";
    [self.brain eraseAllOperands];
}
- (IBAction)enterPressed {
    [self.brain pushOperand: [self.display.text doubleValue]];
    self.display.text = @"0";
    self.userIsInTheMiddleOfEnteringANumber = NO;
}
- (IBAction)operandPressed:(UIButton *)sender {
    double result = [self.brain performOperation:sender.currentTitle];
    NSString *resultString = [NSString stringWithFormat:@"%f",result];
    self.display.text = resultString;
}
- (IBAction)advSwitched:(UISwitch *)sender {
    if (sender.on) {
        [self.plusBtn setTitle:@"^" forState:UIControlStateNormal];
        [self.minusBtn setTitle:@"x√" forState:UIControlStateNormal];
        [self.timesBtn setTitle:@"π" forState:UIControlStateNormal];
        [self.divBtn setTitle:@"÷" forState:UIControlStateNormal];
    } else {
        [self.plusBtn setTitle:@"+" forState:UIControlStateNormal];
        [self.minusBtn setTitle:@"-" forState:UIControlStateNormal];
        [self.timesBtn setTitle:@"X" forState:UIControlStateNormal];
        [self.divBtn setTitle:@"÷" forState:UIControlStateNormal];
    }
}

@end